package Auth;

use Utils;
use SMTPSender;

sub new
{
    my ($class)	= @_;
    my $self	= {
        username	=> '',
        password	=> '',
        realm_id	=> '',
        f_name		=> '',
        l_name		=> '',
        access_ip	=> '',
    };

    bless $self, 'Auth';
    return $self;
}

sub CheckUserExists
{
    my ($self)	= @_;
    my $stmt	= "SELECT count(*) AS ret_val FROM realm WHERE username = \'$self->{username}\'";

    # print $stmt; exit;
    my $kit_db  = new KIT_DB();
    return $kit_db->GetSingleValue($stmt);
}

#	-- Checks password against username
sub CheckPassword
{
    my ($self)	= @_;
    my $stmt	= "SELECT count(*) AS ret_val FROM realm WHERE username = \'$self->{username}\' AND password = \'$self->{password}\'";
    my $kit_db  = new KIT_DB();
    return $kit_db->GetSingleValue($stmt);
}

sub AddUser
{
    my ($self)	= @_;

    my $username	= $self->{username};
    my $password	= $self->{password};
    my $f_name	= $self->{f_name};
    my $l_name	= $self->{l_name};
    my $signup_date	= $Utils::kit_dates->getDate();

    my $stmt	= "INSERT INTO realm (username, password, f_name, l_name, signup_date)
                        VALUES ('$username', '$password', '$f_name', '$l_name', '$signup_date')";

    my $kit_db  = new KIT_DB();
    $kit_db->Insert($stmt);
    # 	print $stmt;
}

#	-- Sets realm
sub GetRealmId
{
    my $self	= shift;
    my $stmt	= "SELECT id ret_val FROM realm WHERE username = '" . $self->{username} . "'";
    my $kit_db  = new KIT_DB();
    return $kit_db->GetSingleValue($stmt);
}

sub kickOut()
{
    my ($self, $cgi_vars)	= @_;
    
    my $app_rel_path	= $Utils::config{'APP_PATH'} . "/cgi-bin/admin/Login.pl";
    print "Access Denied.  You will automatically be redirected for login";
    print "<meta http-equiv=refresh content=2;URL=$app_rel_path />";
    # print "buy a ticket!";
    exit;
}

sub check_account_active
{
    my ($self)	= @_;
    my $stmt	= "SELECT count(*) AS ret_val FROM realm WHERE username = \'$self->{username}\' AND active = 1";

    my $kit_db  = new KIT_DB();
    return $kit_db->GetSingleValue($stmt);
}

sub activate_realm
{
    my ($self)  = @_;
    my $stmt    = "UPDATE realm SET active = 1 WHERE id = " . $self->{realm_id};
    my $kit_db  = new KIT_DB();
    return $kit_db->Update($stmt);
}

sub send_account_activation_email
{
    my ($self)  = @_;

    my $utils       = new Utils();
    my $html_tmpl   = $utils->init_template('Auth/account_activation.email.html');
    my $subject     = "read from <title>";
    my $message     = $html_tmpl->output();

    my %email                   = ();
       $email{recipient_email}  = $self->{username};
       $email{sender_email}     = $Utils::config{ADMIN_EMAIL};
       $email{sender_name}      = 'Keep in Touch Newsletter Tool for Perl Admins';
       $email{subject}          = $subject;
       $email{message}          = $message;

    return (SMTPSender->sendMIMEEmail_HTML(%email));
}
1;